<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
    <!-- 全选区域 -->
    <label class="radio">
      <radio color="#C00000" :checked="isCheckFull" @click="changeAllState" /><text>全选</text>
    </label>

    <!-- 合计区域 -->
    <view class="amount-box"> 合计:<text class="amount">￥ {{checkedMoney.toFixed(2)}}</text> </view>

    <!-- 结算区域 -->
    <view class="btn-settle" @click="settlement">结算({{checkedCount}})</view>
  </view>
</template>

<script>
  import {
    mapGetters,
    mapMutations,
    mapState
  } from 'vuex'
  export default {
    data() {
      return {
        seconds: 3
      }
    },
    computed: {
      ...mapState('m_cart', ['cart']),
      ...mapGetters('m_cart', ['checkedCount', 'total', 'checkedMoney']),
      ...mapGetters('m_user', ['addstr']),
      ...mapState('m_user', ['token']),
      isCheckFull() {
        return this.total === this.checkedCount
      }
    },
    methods: {
      ...mapMutations('m_cart', ['updateAllGoodsState']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      changeAllState() {
        // 把 vuex 中购物车中所有的数据都变为当前全选状态取反的结果
        this.updateAllGoodsState(!this.isCheckFull)
      },
      settlement() {
        // 先判断是否勾选了要结算的商品
        if (this.checkedCount === 0) return uni.$showMsg('请选择要结算的商品！')

        // 再判断用户是否选择了收货地址
        if (!this.addstr) return uni.$showMsg('请选择收货地址！')

        // 最后判断用户是否登录了
        // if (!this.token) return uni.$showMsg('请先登录！')
        // 没有登录,3 秒后跳转到登录页
        if (!this.token) return this.delayNavigate()
        // 支付
        this.payOrder()
      },
      async payOrder() {
        // #1 调用创建订单的接口，目的是为了拿到订单编号
        const orderInfo = {
          // 开发期间，注释掉真实的订单价格
          // order_price: this.checkedGoodsAmount,
          // 写死订单总价为 1 分钱
          order_price: 0.01,
          consignee_addr: this.addstr,
          goods: this.cart.filter(x => x.goods_state)
            .map(x => ({
              goods_id: x.goods_id,
              goods_number: x.goods_count,
              goods_price: x.goods_price
            }))
        }
        const {
          data: res
        } = await uni.$http.post('/my/orders/create', orderInfo)
        if (res.meta.status !== 200) return uni.$showMsg('创建订单失败！')
        console.log(res.message.order_number)
        // #2 根据订单编码调用预支付的接口,目的是为了拿到真正发起微信支付时候的参数
        const orderNumber = res.message.order_number
        const {
          data: res2
        } = await uni.$http.post('/my/orders/req_unifiedorder', {
          order_number: orderNumber
        })
        if (res2.meta.status !== 200) return uni.$showMsg('预付订单生成失败！')
        const payInfo = res2.message.pay
        // #3 发起微信支付
        const [err, succ] = await uni.requestPayment(payInfo)
        if (err) return uni.$showMsg('订单未支付！')
        uni.$showMsg('付款成功')
        // #4 再调用后端的接口查看支付状态
        const {
          data: res3
        } = await uni.$http.post('/my/orders/chkOrder', {
          order_number: orderNumber
        })
        if (res3.meta.status !== 200) return uni.$showMsg('订单未支付！')
        uni.showToast({
          title: '支付完成！',
          icon: 'success'
        })
      },
      delayNavigate() {
        clearInterval(this.timer)
        this.timer = setInterval(() => {
          if (this.seconds === 0) {
            // 跳转
            uni.switchTab({
              url: '/pages/my/my',
              success: () => {
                // 记一下当前页面的地址和跳转方式
                this.updateRedirectInfo({
                  openType: 'switchTab',
                  from: '/pages/cart/cart'
                })
              }
            })
            // 清除定时器
            clearInterval(this.timer)
            // 把 seconds 恢复默认值
            this.seconds = 3
          } else {
            uni.showToast({
              title: `未登录，将在${this.seconds--}秒后跳转到登录页面`,
              duration: 1000,
              mask: true,
              icon: 'none'
            })
          }
        }, 1000)
      }
    }
  }
</script>

<style lang="scss">
  .my-settle-container {
    /* 底部固定定位 */
    position: fixed;
    bottom: 0;
    left: 0;
    /* 设置宽高和背景色 */
    width: 100%;
    height: 50px;
    background-color: white; // 将背景色从 cyan 改为 white

    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 5px;
    font-size: 14px;

    .radio {
      display: flex;
      align-items: center;
    }

    .amount-box {
      .amount {
        color: #c00000;
      }
    }

    .btn-settle {
      height: 50px;
      min-width: 100px;
      background-color: #c00000;
      color: white;
      line-height: 50px;
      text-align: center;
      padding: 0 10px;
    }
  }
</style>
